package edu.dublbo.generator.code.controller;

import edu.dublbo.generator.code.cto.DemoPackageCTO;
import edu.dublbo.generator.code.service.CodeFileService;
import edu.dublbo.generator.common.exception.OptErrorException;
import edu.dublbo.generator.common.result.OptStatus;
import edu.dublbo.generator.common.result.ResponseResult;
import edu.dublbo.generator.common.result.Result;
import edu.dublbo.generator.utils.FileOperator;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping(value = "/code")
public class CodeFileController {
    private static final Logger logger = LoggerFactory.getLogger(CodeFileController.class);

    @Autowired
    private CodeFileService service;


    // 下载多个模型代码
    @GetMapping("/mulDown")
    public void multiDownload(String modelIds, HttpServletResponse response){
        String[] ids = modelIds.split(",");
        Set<String> idSet = new HashSet<>(Arrays.asList(ids));
        try {
            OutputStream os = response.getOutputStream();
            String filename = "generator_" + System.currentTimeMillis() + ".zip";
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
//            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            service.generateCode(idSet, os);
        } catch (IOException e) {
            e.printStackTrace();
            throw new OptErrorException(OptStatus.FAIL.getOptCode(), "文件下载失败");
        }

    }

    // 通过某个模型的 id 加载生成的代码
    @GetMapping(value = "/load/{modelId}")
    public Result<Map<String, Object>> loadCode(@PathVariable String modelId) {
        logger.info("model id : {}", modelId);
        return ResponseResult.generateSuccessResult(service.loadCode(modelId));
    }

//    public ResponseEntity<FileSystemResource> export(File file) {
//        if (file == null) {
//            return null;
//        }
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
//        headers.add("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
//        headers.add("Pragma", "no-cache");
//        headers.add("Expires", "0");
//        return ResponseEntity
//                .ok()
//                .headers(headers)
//                .contentLength(file.length())
//                .contentType(MediaType.parseMediaType("application/octet-stream"))
//                .body(new FileSystemResource(file));
//    }

    // 设置定时任务，定时删除临时生成源码文件
//    @Scheduled(cron = "59 0 11 ? * 5 ")
//    public void deleteTmpDemoFile() {
//        logger.info("定时任务执行：{}", new Date());
//        service.deleteTmpDemoFile();
//    }
}
